﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Fish.Models;
using Fish.DAL;

namespace Fish.Controllers
{

    /** 
    * This class is responsible for creating and displaying the transportation tab.
    */
    [Authorize]
    public class TransportsController : Controller
    {
        private FishContext db = new FishContext();

        // GET: /Transports/
        public ActionResult Index(int? errorNum)
        {

            if (Session["eventID"] != null)
            {
                int eventID = int.Parse(Session["eventID"].ToString());
                List<Transports> transportsEvents = db.Transports.Where(e => e.Event.ID == eventID).ToList();
                String error = "";
                System.Diagnostics.Debug.WriteLine("Error number: " + errorNum);
                if (errorNum != null)
                {
                    if (errorNum == 1)
                    {
                        error = "You are already going";
                    }
                    if (errorNum == 2)
                    {
                        error = "There are no more places in this car";
                    }
                    System.Diagnostics.Debug.WriteLine("Error: " + error);
                    ModelState.AddModelError("", error);
                }
                if (transportsEvents != null)
                {
                    return View(transportsEvents);
                }
                else
                {
                    return RedirectToAction("Index", "EventUserRelations");
                }
            }
            else
                return RedirectToAction("Expired", "Error");

        }

        // GET: /Transports/Details/5
        public ActionResult Details(int? id)
        {

            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Transports transports = db.Transports.Find(id);
            if (transports == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(transports);
        }

        /** 
        * This method displays the passengers who should be picked up.
        */
        public ActionResult ViewPassengers(int id)
        {
            Transports myTransport = db.Transports.Find(id);
            List<Users> passengers = myTransport.Passengers.ToList();
            ViewBag.passengers = passengers;
            return View();
        }
        // GET: /Transports/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Transports/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,UsersID,UserName,ComingFrom,CarDescription,NumberOfPlaces,Created,Modified")] Transports transports, string button)
        {
            System.Diagnostics.Debug.WriteLine("HENA");
            int eventID = int.Parse(Session["eventID"].ToString());
            if (ModelState.IsValid)
            {
                System.Diagnostics.Debug.WriteLine("HENA2");

                int userID = int.Parse(Session["userID"].ToString());
                string userName = db.Users.Find(userID).Username;

                transports.UsersID = userID;
                transports.UserName = userName;
                transports.Event = db.Events.Find(eventID);
                db.Transports.Add(transports);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(transports);
        }

        /** 
        * This method is responsible for adding the users who should be picked up to the passengers list
         * and decreasing the number of the available places. Also this passneger is added to the list
         * of responsibilities of the driver.
        */

        public ActionResult AddPassanger(int id)
        {
            Transports myTransport = db.Transports.Find(id);
            if (myTransport.NumberOfPlaces != 0)
            {
                int passangerID = int.Parse(Session["userID"].ToString());
                Users passenger = db.Users.Find(passangerID);
                if (!myTransport.Passengers.Contains(passenger))
                {
                    myTransport.Passengers.Add(passenger);
                    myTransport.NumberOfPlaces = myTransport.NumberOfPlaces - 1;
                    int userID = myTransport.UsersID;

                    EventUserRelations eur = db.EventUserRelations.Where(e => e.EventsID == myTransport.Event.ID && e.UsersID == userID).FirstOrDefault();
                    System.Diagnostics.Debug.WriteLine("EUR ID: " + eur.ID);
                    string newTaskTxt = "Take " + passenger.Username + " with you ";
                    MyTask newTask = new MyTask(); newTask.taskMsg = newTaskTxt;
                    eur.Tasks.Add(newTask);
                    db.SaveChanges();
                }
                else
                {
                    return RedirectToAction("Index", new { errorNum = 1 });
                }
            }
            else
            {
                return RedirectToAction("Index", new { errorNum = 2 });
            }
            return RedirectToAction("Index");
        }

        // GET: /Transports/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Transports transports = db.Transports.Find(id);
            if (transports == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(transports);
        }

        // POST: /Transports/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,UsersID,UserName,ComingFrom,CarDescription,NumberOfPlaces,Created,Modified")] Transports transports)
        {
            if (ModelState.IsValid)
            {
                db.Entry(transports).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(transports);
        }

        // GET: /Transports/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Transports transports = db.Transports.Find(id);
            if (transports == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(transports);
        }

        // POST: /Transports/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Transports transports = db.Transports.Find(id);
            db.Transports.Remove(transports);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
